import requests
from bs4 import BeautifulSoup
import re
import datetime

def wanzhengbifen_main(date):
    
    url = f"https://bf.titan007.com/football/Over_{date}.htm"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
    }

    response = requests.get(url, headers=headers)
    response.encoding = 'gbk'

    html_content = response.text

    soup = BeautifulSoup(html_content, 'html.parser')

    date = datetime.datetime.strptime(date, "%Y%m%d").strftime("%Y-%m-%d")
    def clean_team_name(team_text):
        """
        清理球队名称，去除方括号内的内容（如[10]、[西4]等）
        """
        # 使用正则表达式去除方括号及其内部内容
        cleaned_text = re.sub(r'\[[^\]]*\]', '', team_text)
        # 规范化空白字符
        cleaned_text = ' '.join(cleaned_text.split())
        return cleaned_text.strip()

    # 提取表格中的数据
    table = soup.find('table', id='table_live')
    if table:
        # 获取所有行（跳过表头）
        rows = table.find_all('tr')[1:]  # 跳过表头

        list_data = []  # 这里应该是存储所有比赛数据的列表
        for row in rows:
            # 获取行中的所有单元格
            cells = row.find_all('td')
            if cells and len(cells) >= 10:  # 确保至少有6列
                # 提取第1、4、6列数据 (索引0, 3, 5)
                try:
                    league = cells[0].get_text(strip=True)
                    home_team = cells[3].get_text(strip=True)
                    away_team = cells[5].get_text(strip=True)
                    
                    # 清理球队名称，去除方括号内容
                    home_team = clean_team_name(home_team)
                    away_team = clean_team_name(away_team)
                    
                    # 提取第九个单元格中的第二个a标签的onclick参数
                    ninth_cell = cells[9]  # 第九个单元格（索引8）
                    a_tags = ninth_cell.find_all('a')
                    
                    pid = None
                    if len(a_tags) >= 2:
                        # 获取第二个a标签的onclick属性
                        onclick_attr = a_tags[1].get('onclick')
                        if onclick_attr:
                            # 使用正则表达式提取括号内的数字
                            match = re.search(r'AsianOdds\((\d+)\)', onclick_attr)
                            if match:
                                pid = match.group(1)
                    
                    # 组合数据
                    match_data = {  # 改变变量名避免混淆
                        'league': league,
                        'home_team': home_team,
                        'away_team': away_team,
                        'pid': pid,
                        'pidtime': date
                    }
                    list_data.append(match_data)  # 正确地向列表添加字典

                except IndexError:
                    # 处理可能的索引错误
                    continue
        return list_data
    else:
        print("未找到ID为'table_live'的表格")
        return []



if __name__ == "__main__":
    # 2025年10月9日
    date = "20251013"

    result = wanzhengbifen_main(date)
    for item in result:
        print(item)
    # 写入到json文件
    import json
    with open('output.json', 'w', encoding='utf-8') as json_file:
        json.dump(result, json_file, ensure_ascii=False, indent=4)
